package com.mind.adjust.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mind.adjust.mapper.AjMonthReportMapper;
import com.mind.adjust.mapper.AjRuleDetailMapper;
import com.mind.adjust.mapper.TicketTaskCountMapper;
import com.mind.cache.lock.annotation.DMLock;
import com.mind.common.utils.DateUtils;
import com.mind.customer.mapper.AjCheckResultMapper;
import com.mind.customer.mapper.AjTicketTaskMapper;
import com.mind.quartz.mapper.*;
import com.mind.system.domain.*;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@Component
@Log4j2
public class SyncRulePassService {
    @Resource
    private AjCheckResultMapper checkResultMapper;
    @Resource
    private AjRuleDetailMapper ruleDetailMapper;
    @Resource
    private DayReportMapper dayReportMapper;
    @Resource
    private AjTicketTaskMapper ticketTaskMapper;
    @Resource
    private AjMonthReportMapper monthReportMapper;
    @Resource
    private TicketTaskCountMapper ticketTaskCountMapper;

    @DMLock(key = "syncRulePassTask")
    public void syncRulePass() {
        syncRulePassByDate(new Date());
    }

    public void syncRulePassByDate(Date date) {
        log.info("开始同步{}的规则通过情况", DateUtils.parseDateToStr("yyyy-MM-dd", date));
        // 查询当天检查结果
        QueryWrapper<AjCheckResult> queryWrapper = new QueryWrapper<>(new AjCheckResult() {{
            setStartCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", date));
            setEndCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", date));
        }});
        List<AjCheckResult> checkResultList = checkResultMapper.selectList(queryWrapper);
        Map<String, AjDayReport> dayReportMap = new HashMap<>();
        for (AjCheckResult checkResult : checkResultList) {
            AjDayReport dayReport = dayReportMap.get(checkResult.getRuleName());
            if (dayReport == null && checkResult.getRuleDetailId() != null) {
                AjRuleDetail detail = ruleDetailMapper.selectOne(new QueryWrapper<>(new AjRuleDetail() {{
                    setId(checkResult.getRuleDetailId().intValue());
                }}));
                if (detail != null) {
                    dayReport = new AjDayReport();
                    dayReport.setRuleName(checkResult.getRuleName());
                    dayReport.setRuleType(detail.getAttachCate());
                    dayReport.setRuleset(detail.getRuleGroup());
                    dayReport.setDay(DateUtils.parseDateToStr("yyyy-MM-dd", date));
                    dayReport.setPassCount(0);
                    dayReport.setTotalCount(0);
                    dayReportMap.put(checkResult.getRuleName(), dayReport);
                }
            }
            if (dayReport != null) {
                if (checkResult.getStatus() == 1) {
                    dayReport.setPassCount(dayReport.getPassCount() + 1);
                }
                if (Arrays.asList(1, 2, 3).contains(checkResult.getStatus())) {
                    dayReport.setTotalCount(dayReport.getTotalCount() + 1);
                }
            }
        }

//        List<AjDayReport> dayReportList = new ArrayList<>(dayReportMap.values());
        for (AjDayReport dayReport : dayReportMap.values()) {
            AjDayReport report = dayReportMapper.selectOne(new QueryWrapper<>(new AjDayReport() {
                {
                    setDay(dayReport.getDay());
                    setRuleName(dayReport.getRuleName());
                }
            }
            ));
            if (report == null) {
                dayReportMapper.insert(dayReport);
            } else {
                report.setPassCount(dayReport.getPassCount());
                report.setTotalCount(dayReport.getTotalCount());
                dayReportMapper.updateById(report);
            }
        }
    }

    @DMLock(key = "syncHistoryRulePass")
    public void syncHistoryRulePass() {
        List<Date> dates = DateUtils.getAllDatesBetween(DateUtils.parseDate("2024-09-01"), new Date());
        for (Date date : dates) {
            syncRulePassByDate(date);
        }
    }

    @DMLock(key = "syncHistoryTickTaskPass")
    public void syncHistoryTickTaskPass() {
        List<Date> dates = DateUtils.getAllDatesBetween(DateUtils.parseDate("2024-09-01"), new Date());
        for (Date date : dates) {
            syncTickTaskPassByDate(date);
        }
    }

    private void syncTickTaskPassByDate(Date date) {
        QueryWrapper<AjTicketTask> queryWrapper = new QueryWrapper<>(new AjTicketTask() {{
            setStartCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", date));
            setEndCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", date));
            setTotalCount(0L);
        }});
        List<AjTicketTask> ticketTaskList = ticketTaskMapper.selectList(queryWrapper);
        for (AjTicketTask ticketTask : ticketTaskList) {
//
            Long passCount = checkResultMapper.selectCount(new QueryWrapper<>(new AjCheckResult() {
                {
                    setTicketId(ticketTask.getTicketId());
                    setVersion(ticketTask.getVersion());
                    setStatus(1);
                }
            }
            ));

            QueryWrapper<AjCheckResult> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("ticket_id", ticketTask.getTicketId());
            updateWrapper.eq("version", ticketTask.getVersion());
            updateWrapper.in("status", Arrays.asList(1, 2, 3));

            Long totalCount = checkResultMapper.selectCount(updateWrapper);
            ticketTaskMapper.updateById(new AjTicketTask() {{
                setId(ticketTask.getId());
                setCheckResult(Objects.equals(passCount, totalCount) ? 1 : 2);
                setPassCount(passCount);
                setTotalCount(totalCount);
            }});
        }
    }

    public void syncRulePassRate(String startTime, String endTime) {
        String startMonth = DateUtils.parseDateToStr("yyyy-MM", DateUtils.parseDate(startTime)), endMonth = DateUtils.parseDateToStr("yyyy-MM", DateUtils.parseDate(endTime));
        int queryType = 2;
        String yearMonth = DateUtils.parseDateToStr("yyyy", DateUtils.parseDate(startTime));
        if (startMonth.equals(endMonth)) {
            queryType = 1;
            yearMonth = startMonth;
        }
        List<AjRuleDetail> ruleDetails = ruleDetailMapper.selectList(null);
        Page<AjCheckResult> page = new Page<>(1, 1000);
        page.addOrder(OrderItem.desc("create_time"));
        for (AjRuleDetail detail : ruleDetails) {
            QueryWrapper<AjCheckResult> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("rule_detail_id", detail.getId());
            updateWrapper.ge("create_time", startTime);
            updateWrapper.le("create_time", endTime);
            updateWrapper.in("status", Arrays.asList(1, 2, 3));
            Page<AjCheckResult> ajCheckResultPage = checkResultMapper.selectPage(page, updateWrapper);
            List<AjCheckResult> checkResultList = ajCheckResultPage.getRecords();
            long passCount = checkResultList.stream().filter(checkResult -> checkResult.getStatus() == 1).count();
            long totalCount = checkResultList.size();
            String finalYearMonth = yearMonth;
            int finalQueryType = queryType;
            AjMonthReport ajMonthReport = monthReportMapper.selectOne(new QueryWrapper<>(new AjMonthReport() {{
                setRuleName(detail.getName());
                setYearMonth(finalYearMonth);
                setQueryType(finalQueryType);
            }}));
            int failCount = (int) ((int) totalCount-passCount);
            if(ajMonthReport == null) {
                monthReportMapper.insert(new AjMonthReport() {{
                    setRuleName(detail.getName());
                    setPassCount((int) passCount);
                    setTotalCount((int) totalCount);
                    setYearMonth(finalYearMonth);
                    setFailCount(failCount);
                    setFailRate(totalCount == 0 ? "0":String.format( "%.2f", failCount * 1.0 / totalCount * 100));
                    setQueryType(finalQueryType);
                }});
            }else{
                monthReportMapper.updateById(new AjMonthReport() {{
                    setId(ajMonthReport.getId());
                    setPassCount((int) passCount);
                    setFailCount(failCount);
                    setFailRate(String.format(totalCount == 0 ? "0": "%.2f", failCount * 1.0 / totalCount * 100));
                    setTotalCount((int) totalCount);
                }});
            }
        }

    }

    public void syncRuleCurrentPassRate() {
        LocalDate[] monthStartAndEnd = DateUtils.getMonthStartAndEnd(DateUtils.getDate());
        syncRulePassRate(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", Date.from(monthStartAndEnd[0].atStartOfDay(ZoneId.systemDefault()).toInstant())), DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", Date.from(monthStartAndEnd[1].atStartOfDay(ZoneId.systemDefault()).toInstant())));
        LocalDate[] yearStartAndEnd = DateUtils.getYearStartAndEnd();
        syncRulePassRate(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", Date.from(yearStartAndEnd[0].atStartOfDay(ZoneId.systemDefault()).toInstant())), DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", Date.from(yearStartAndEnd[1].atStartOfDay(ZoneId.systemDefault()).toInstant())));
    }



    public void syncHistoryRulePassRate() {

    }
    @DMLock(key = "syncHistoryTicketTaskCount")
    public void syncHistoryTicketTaskCount() {
        List<Date> dates = DateUtils.getAllDatesBetween(DateUtils.parseDate("2024-09-01"), new Date());
        for (Date date : dates) {
            log.info("同步tickTaskCount {} 开始", date);
            syncTicketTaskCountByDate(date);
        }
    }
    @DMLock(key = "syncCurrentTicketTaskCount")
    public void syncTicketTaskCount() {
        syncTicketTaskCountByDate(new Date());
    }


    public void syncTicketTaskCountByDate(Date date) {
        int count = ticketTaskMapper.selectByDate(
                DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", date),
                DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", date));
        AjTicketTaskCount ajTicketTaskCount = ticketTaskCountMapper.selectOne(new QueryWrapper<>(new AjTicketTaskCount() {{
                    setDay(DateUtils.parseDateToStr("yyyy-MM-dd", date));
        }}));
        if(ajTicketTaskCount == null) {
            ticketTaskCountMapper.insert(new AjTicketTaskCount() {{
                setCount(count);
                setDay(DateUtils.parseDateToStr("yyyy-MM-dd", date));
            }});
        }else{
            ticketTaskCountMapper.updateById(new AjTicketTaskCount() {{
                setId(ajTicketTaskCount.getId());
                setCount(count);
            }});
        }

    }
}
